﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SD.Infrastructure.AspNetCore.Filters;
using SD.Infrastructure.AspNetCore.Server.Middlewares;
using SD.IOC.Core.Mediators;
using SD.IOC.Extension.NetCore;
using System;

namespace AspNetCore.Practice.AppService
{
    /// <summary>
    /// 引导
    /// </summary>
    public class Startup
    {
        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造器
        /// </summary>
        public Startup(IConfiguration configuration)
        {
            this._configuration = configuration;
        }


        /// <summary>
        /// 配置依赖注入
        /// </summary>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //配置HttpContext访问器
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            //配置MVC
            services.AddMvc(options =>
            {
                options.Filters.Add<ExceptionFilter>();
            });

            //配置依赖注入
            IServiceCollection builder = ResolveMediator.GetServiceCollection();
            foreach (ServiceDescriptor descriptor in services)
            {
                builder.Add(descriptor);
            }

            builder.RegisterConfigs();
            ResolveMediator.Build();

            IServiceProvider serviceProvider = ResolveMediator.GetServiceProvider();

            return serviceProvider;
        }

        /// <summary>
        /// 配置应用程序
        /// </summary>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //配置全局中间件
            app.UseMiddleware<GlobalMiddleware>();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
